package files

import (
	"fmt"
	"os"
	"path/filepath"
	"time"
)

type File struct {
}

func (F File) MakeSaveFolderByYear(dir string) string {
	folderPath := filepath.Join(dir, time.Now().Format("2006"))
	F.MakeSavePathCheck(folderPath)
	return folderPath
}

func (F File) MakeSaveFolderByMonth(dir string) string {
	folderPath := filepath.Join(dir, time.Now().Format("2006-01"))
	F.MakeSavePathCheck(folderPath)
	return folderPath
}

func (F File) MakeSaveFolderByDate(dir string) string {
	folderPath := filepath.Join(dir, time.Now().Format("2006-01-02"))
	F.MakeSavePathCheck(folderPath)
	return folderPath
}

func (F File) MakeSavePathByYear(dir string, fileName string) string {
	fileName = filepath.Join(dir, time.Now().Format("2006"), fileName)
	F.MakeSavePathCheck(fileName)
	return fileName
}

func (F File) MakeSavePathByMonth(dir string, fileName string) string {
	fileName = filepath.Join(dir, time.Now().Format("2006-01"), fileName)
	F.MakeSavePathCheck(fileName)
	return fileName
}

func (F File) MakeSavePathByDate(dir string, fileName string) string {
	fileName = filepath.Join(dir, time.Now().Format("2006-01-02"), fileName)
	F.MakeSavePathCheck(fileName)
	return fileName
}

func (F File) MakeSavePathCheck(path string) {
	if !F.FileIsExists(path) {
		_ = os.MkdirAll(path, os.ModePerm)
	}
}

// FileIsExists
/*
@Description: 检查文件是否存在
@param path
@return bool
*/
func (F File) FileIsExists(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		if os.IsExist(err) {
			return true
		}
		return false
	}
	return !s.IsDir()
}

// FormatFileSize
/*
@Description: 转换文件单位
@param fileSize 文件大小
@return size 字符串
*/
func (F File) FormatFileSize(fileSize float64) (size string) {
	units := []string{"B", "KB", "MB", "GB", "TB"}
	var unitIndex int
	for fileSize >= 1024 && unitIndex < len(units)-1 {
		fileSize /= 1024
		unitIndex++
	}
	return fmt.Sprintf("%.2f %s", fileSize, units[unitIndex])
}
